#include "NMPreHeader.h"
#include "NMSceneGame.h"
#include "NMGun.h"
#include "NMBulletMgr.h"
#include "NMEnemyMgr.h"
#include "NMEnemyBulletMgr.h"

CCScene* NMLayerGame::scene()
{
	FUNCTION_ENTER();

	CCScene* scene = CCScene::node();

	NMLayerGame* layer = NMLayerGame::node();

	scene->addChild(layer);

	FUNCTION_LEAVE();

	return scene;
}

bool NMLayerGame::init()
{
	FUNCTION_ENTER();

	CCLayer::init();

	_isTouched = false;
	_curTouch = NULL;

	setIsTouchEnabled(true);

	// background
	CCSprite* bg = CCSprite::spriteWithFile("bg1.png");
	bg->setPosition(gPointCenter);
	addChild(bg, layerBg);

	// Attack Area
	CCSprite* aar = CCSprite::spriteWithFile("attack_area.png");
	aar->setPosition(ccp(160,150));
	addChild(aar);

	NMGun::shared()->addToLayer(this);
	NMEnemyMgr::shared()->addToLayer(this);
	NMBulletMgr::shared()->addToLayer(this);
	NMEnemyBulletMgr::shared()->addToLayer(this);

	_layerUI = new NMMainUI();
	addChild(_layerUI, 100);

	scheduleUpdate();

	FUNCTION_LEAVE();

	return true;
}

void NMLayerGame::update(ccTime dt)
{
	FUNCTION_ENTER();

	NMGun::shared()->update(dt);
	NMBulletMgr::shared()->update(dt);
	NMEnemyBulletMgr::shared()->update(dt);
	NMEnemyMgr::shared()->update(dt);

	_layerUI->update(dt);

	FUNCTION_LEAVE();
}

void NMLayerGame::registerWithTouchDispatcher()
{
	FUNCTION_ENTER();

	CCTouchDispatcher::sharedDispatcher()->addStandardDelegate(this, 0);

	FUNCTION_LEAVE();
}

void NMLayerGame::ccTouchesBegan(CCSet* touches, CCEvent* evt)
{
	FUNCTION_ENTER();

	CCTouch* touch;
	CCSetIterator setIter;

	if(!_isTouched)
	{
		for(setIter = touches->begin(); setIter != touches->end(); ++setIter)
		{
			touch = (CCTouch*)(*setIter);
			CCPoint pos = convertTouchToNodeSpace(touch);

			_isTouched = true;
			_curTouch = touch;
			
			NMGun::shared()->setFire(true);
			NMGun::shared()->setAngle(_getAngle(pos));
		}
	}

	FUNCTION_LEAVE();
}

void NMLayerGame::ccTouchesMoved(CCSet* touches, CCEvent* evt)
{
	FUNCTION_ENTER();

	if(_isTouched && touches->containsObject(_curTouch))
	{
		CCPoint pos = convertTouchToNodeSpace(_curTouch);
		NMGun::shared()->setAngle(_getAngle(pos));
	}

	FUNCTION_LEAVE();
}

void NMLayerGame::ccTouchesEnded(CCSet* touches, CCEvent* evt)
{
	FUNCTION_ENTER();

	if(_isTouched && touches->containsObject(_curTouch))
	{
		_isTouched = false;
		_curTouch = NULL;
		NMGun::shared()->setFire(false);
	}

	FUNCTION_LEAVE();
}

void NMLayerGame::ccTouchesCancelled(CCSet* touches, CCEvent* evt)
{
	FUNCTION_ENTER();

	if(_isTouched && touches->containsObject(_curTouch))
	{
		_isTouched = false;
		_curTouch = NULL;
		NMGun::shared()->setFire(false);
	}

	FUNCTION_LEAVE();
}

float NMLayerGame::_getAngle(CCPoint pos)
{
	FUNCTION_ENTER();

	pos.x -= 160.f;
	float dis = ccpLength(pos);

	FUNCTION_LEAVE();

	return CC_RADIANS_TO_DEGREES(asin(pos.x / dis));
}
